package org.skatiger.jrove.component.html;

import java.io.IOException;

import org.skatiger.jrove.ResponseWriter;
import org.skatiger.jrove.ViewContext;
import org.skatiger.jrove.component.JroveAttr;
import org.skatiger.jrove.component.UIResource;
import org.skatiger.jrove.renderer.Html;
import org.skatiger.jrove.renderer.RendererUtils;
import org.skatiger.jrove.util.StringUtils;

public class HtmlJavascript extends UIResource {
    private String charset;
    private String defer;

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public String getCharset() {
        return getPropertyValue("charset", charset);
    }

    public void setDefer(String defer) {
        this.defer = defer;
    }

    public String getDefer() {
        return getPropertyValue("defer", defer);
    }

    @Override
    public boolean getRendersChildren() {
        return true;
    }

    @Override
    public void encodeChildren(ViewContext context) throws IOException {
        super.encodeChildren(context);
        boolean hasValue = StringUtils.isNotBlank(getValue());
        ResponseWriter writer = context.getResponseWriter();
        writer.startElement(Html.SCRIPT_ELEM, this);
        writer.writeAttribute(Html.TYPE_ATTR, Html.SCRIPT_TYPE_TEXT_JAVASCRIPT,
                JroveAttr.TYPE_ATTR);
        RendererUtils.renderHtmlAttribute(writer, this, Html.CHARSET_ATTR);
        if (hasValue) {
            String _value = UIResource.getResourceURL(context, getValue());
            writer.writeAttribute(Html.SRC_ATTR, _value, JroveAttr.VALUE_ATTR);
        } else {
            super.encodeChildren(context);
        }
        writer.endElement(Html.SCRIPT_ELEM);
    }

}
